package com.why.controller;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.why.aop.LogAnn;
import com.why.entity.Result;
import com.why.entity.User;
import com.why.service.IUserService;
import com.why.utils.JwtUtils;
import com.zhenzi.sms.ZhenziSmsClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hy-woo
 * @since 2022-06-07
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    IUserService userService;
    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping("/getTelCode")
    public Result getTelCode(@RequestBody User user) throws Exception {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("tel",user.getTel());
        User u1 = userService.getOne(wrapper);
        if (u1==null){
            return new Result(909,"","用户不存在");
        }
        String code = RandomUtil.randomInt(1000, 9999)+"";
        redisTemplate.opsForValue().set(user.getCodeKey(),code,5,TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(user.getCodeKey()+"tel",user.getTel(),5,TimeUnit.MINUTES);
        ZhenziSmsClient client = new ZhenziSmsClient("https://sms_developer.zhenzikj.com", "111292", "\n" +
                "f7ab991d-1ae0-4d51-b9bf-8bf5716316bf");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("number", u1.getTel());
        params.put("templateId", "8771");
        String[] templateParams = new String[2];
        templateParams[0] = code;
        templateParams[1] = "5分钟";
        params.put("templateParams", templateParams);
        String result = client.send(params);
        return new Result(200,"","发送成功");
    }

    @RequestMapping("/mylogin")
    public Result login(@RequestBody User user){
        if (!user.getTel().equals((String) redisTemplate.opsForValue().get(user.getCodeKey()+"tel"))){
            return new Result(911,"","手机号错误");
        }
        if (!user.getTelCode().equals((String) redisTemplate.opsForValue().get(user.getCodeKey()))){
            return new Result(909,"","验证码错误");
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("tel",user.getTel());
        User u1 = userService.getOne(wrapper);
        if (u1==null){
            return new Result(910,"","用户不存在");
        }
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(u1.getUsername(), u1.getPassword());
        try {
            Authentication authenticate = authenticationManager.authenticate(upToken);
            User ylogin = (User) authenticate.getPrincipal();
            String token = JwtUtils.createToken(ylogin.getUsername(), 30, JSONUtil.toJsonStr(ylogin));
            redisTemplate.opsForValue().set(ylogin.getUsername(),authenticate,30, TimeUnit.MINUTES);
            HashMap<String,Object> map=new HashMap<>();
            map.put("token",token);
            map.put("user",ylogin);
            return new Result(200,"",map);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("============"+e);
            return new Result(908,"","看后台报错");
        }
    }

}
